<template>
  <div class="app-container">

    <div class="card-wrap padding20 flex">

      <div v-for="(item, index) in tabs" :key="index" @click="tabClick(index)" :class="item.check?'tab-active':'tab-normal'">
        {{ item.name }}({{ item.count }})
      </div>

    </div>

    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">

      <el-col :span="6">
        <el-form-item label="客户编码:" prop="customerCode">
          <el-input maxlength="30" v-model="queryParams.customerCode" clearable placeholder="请输入客户编码"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="客户名称:" prop="customerName">
          <el-input maxlength="30" v-model="queryParams.customerName" clearable placeholder="请输入客户名称"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="客户属性:" prop="customerPropertyCode">
          <el-select filterable v-model="queryParams.customerPropertyCode" clearable>
            <template v-for="dict in dict.type.customer_property">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="客户等级:" prop="customerLevelCode">
          <el-select filterable v-model="queryParams.customerLevelCode" clearable>
            <template v-for="dict in dict.type.customer_level">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="创建人:" prop="createBy">
          <el-input maxlength="30" v-model="queryParams.createBy" clearable placeholder="请输入创建人名称"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="客户标签:" prop="customerLabelCode">
          <el-select filterable v-model="queryParams.customerLabelCode" clearable>
            <template v-for="dict in dict.type.customer_label">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="来源:" prop="customerSourceCode">
          <el-select filterable v-model="queryParams.customerSourceCode" clearable>
            <template v-for="dict in dict.type.customer_source">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="创建时间:" prop="createStartTime">
          <el-date-picker v-model="timeRange" type="daterange" align="left" unlink-panels range-separator="至" value-format="yyyy-MM-dd" format="yyyy-MM-dd" start-placeholder="开始时间" end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="业务范围:" prop="businessScopeCode">
          <el-select filterable clearable v-model="queryParams.businessScopeCode">
            <template v-for="dict in dict.type.business_scope">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="统一信用代码:" prop="customerUscc">
          <el-input maxlength="30" v-model="queryParams.customerUscc" clearable placeholder="请输入统一信用代码"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="证件号码:" prop="identityNumber">
          <el-input maxlength="30" v-model="queryParams.identityNumber" clearable placeholder="请输入证件号码"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="提交状态:" prop="saveFlag">
          <el-select filterable clearable v-model="queryParams.saveFlag">
            <el-option :label="'已暂存'" :value="0" :key="0"></el-option>
            <el-option :label="'已保存'" :value="1" :key="1"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </SearchContent>

    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
        <el-button type="primary" size="mini" @click="handleAdd" v-hasPermi="['memberClue:memberList:add']">新增
        </el-button>
        <el-button type="success" size="mini" @click="handleExport" v-hasPermi="['memberClue:memberList:export']">导出
        </el-button>
        <el-button type="warning" size="mini" @click="handleImport" v-hasPermi="['memberClue:memberList:batchadd']">批量添加
        </el-button>
        <!--        <el-button type="primary" plain size="mini" @click="handleQuota"-->
        <!--                   v-hasPermi="['demo:demo:add']">额度查看</el-button>-->
        <!--        <el-button type="primary" plain size="mini" @click="handlePublic"-->
        <!--                   v-hasPermi="['demo:demo:add']">共用额度客户</el-button>-->
        <!--        <el-button type="primary" plain size="mini" @click="handleTransfer"-->
        <!--                   v-hasPermi="['demo:demo:add']">开票信息</el-button>-->
        <!--        <el-button type="primary" plain size="mini" @click="handleDetail"-->
        <!--                   v-hasPermi="['demo:demo:add']">客户详情</el-button>-->
      </div>

      <table-page :loading="loading" :dataList="dataList" border :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @setSizeCurrent="getList">
        <!-- 操作插槽 -->
        <template slot="tableColAc">
          <el-table-column label="操作" min-width="300" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <e-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['memberClue:memberList:edit']">编辑
              </e-button>
              <e-button size="mini" type="text" @click="handleDelete(scope.row)" v-hasPermi="['memberClue:memberList:delete']">删除
              </e-button>
              <e-button size="mini" type="text" @click="handleDetail(scope.row)" v-hasPermi="['memberClue:memberList:view']">查看
              </e-button>
              <e-button size="mini" type="text" @click="handleQuota(scope.row)" v-hasPermi="['memberClue:memberList:quota']">额度查看
              </e-button>
              <!--                            <e-button size="mini" type="text" icon="el-icon-document" @click="handlePublic(scope.row)"-->
              <!--                                      v-hasPermi="['demo:demo:remove']">共用额度客户-->
              <!--                            </e-button>-->
              <e-button size="mini" type="text" @click="handleTransfer(scope.row)" v-hasPermi="['memberClue:memberList:invoice']">开票信息
              </e-button>
<!--              <e-button size="mini" type="text" @click="distribution(scope.row)" v-if="1 == scope.row.saveFlag" v-hasPermi="['memberClue:memberList:distribution']">分配-->
<!--              </e-button>-->
            </template>
          </el-table-column>
        </template>
        <!-- 普通列插槽 -->
        <template slot="tableCol">
          <el-table-column show-overflow-tooltip label="业务范围" min-width="90" align="center" prop="businessScopeCode">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.business_scope" :value="scope.row.businessScopeCode" />
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="客户编码" min-width="190" align="center" prop="customerCode">
            <template v-slot="{row}">
              {{ row.customerCode|filterNull }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="客户名称" min-width="130" align="center" prop="customerName">
            <template v-slot="{row}">
              {{ row.customerName|filterNull }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="客户属性" min-width="90" align="center" prop="customerProperty">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.customer_property" :value="scope.row.customerPropertyCode" />
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="客户等级" min-width="90" align="center" prop="customerLevelCode" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.customer_level" :value="scope.row.customerLevelCode" />
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="来源" min-width="90" align="center" prop="customerSource">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.customer_source" :value="scope.row.customerSourceCode" />
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="客户标签" min-width="130" align="center" prop="customerLabel">
            <template v-slot="{row}">
              {{ row.customerLabel|filterNull }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="提交状态" min-width="100" align="center" prop="saveFlag">
            <template v-slot="{row}">
              {{ 0 == row.saveFlag ? '已暂存' : 1 == row.saveFlag ? '已保存' : '--' }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="是否为老客户" min-width="100" align="center" prop="customerOldType">
            <template slot-scope="scope">
              {{ 1 == scope.row.customerOldType ? '是' : 2 == scope.row.customerOldType ? '否' : '--' }}
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip label="统一信用代码" min-width="190" align="center" prop="customerUscc">
            <template v-slot="{row}">
              {{ row.customerUscc|filterNull }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="证件号码" min-width="190" align="center" prop="identityNumber">
            <template v-slot="{row}">
              {{ row.identityNumber|filterNull }}
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip label="联系电话" min-width="115" align="center" prop="customerPhone">
            <template v-slot="{row}">
              {{ row.customerPhone|filterNull }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="创建人" min-width="130" align="center" prop="createBy">
            <template v-slot="{row}">
              {{ row.createBy|filterNull }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="创建时间" min-width="150" align="center" prop="createTime">
            <template v-slot="{row}">
              {{ row.createTime|filterNull }}
            </template>
          </el-table-column>
        </template>
      </table-page>

    </div>

    <!-- 添加或修改测试单表对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="45%">
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">

        <el-row>
          <el-col :span="20">
            <el-form-item :label="2==form.customerTypeCode?'客户公司名称:':'客户名称'" prop="invoiceTitle">
              <el-input v-model="form.invoiceTitle" clearable placeholder="请输入客户名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20" v-if="2==form.customerTypeCode">
            <el-form-item label="税号:" prop="taxpayerIdentityNumber">
              <el-input v-model="form.taxpayerIdentityNumber" clearable placeholder="请输入税号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="开户银行:" prop="bankName">
              <el-input v-model="form.bankName" clearable placeholder="请输入开户银行"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="账户:" prop="bankAccountName">
              <el-input v-model="form.bankAccountName" clearable placeholder="请输入账户"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="地址:" prop="invoiceAddr">
              <el-input v-model="form.invoiceAddr" clearable placeholder="请输入地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="联系电话:" prop="invoicePhone">
              <el-input v-model="form.invoicePhone" clearable placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="收件人:" prop="recipients">
              <el-input v-model="form.recipients" clearable placeholder="请输入收件人"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">{{ isNew ? '取消' : '关闭' }}</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="isNew">确 定</el-button>
      </div>
    </el-dialog>

    <!--    共用额度客户-->
    <el-dialog title="共用额度客户" :visible.sync="publicOpen" append-to-body width="45%">
      <el-form ref="publicForm" :rules="publicRules" :model="publicForm" label-width="120px">

        <el-row>
          <el-col :span="20">
            <el-form-item label="客户名称:" prop="contactPhone">
              <el-input disabled v-model="publicForm.contactPhone" clearable placeholder="请选择"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="共用额度客户:" prop="intentionLevel">
              <el-select v-model="publicForm.intentionLevel" clearable style="width: 100%">
                <template v-for="dict in dict.type.sys_order_source">
                  <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="20">
            <el-form-item label="描述:" prop="remark">

              <el-input v-model="publicForm.remark" type="textarea" :rows="2" clearable placeholder="请输入描述"></el-input>

            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="publicCancel">{{ isNew ? '取消' : '关闭' }}</el-button>
        <el-button :loading="publicLoading" type="primary" v-if="isNew">确 定</el-button>
      </div>
    </el-dialog>

    <!--    额度查看-->
    <el-dialog title="额度查看" :visible.sync="quotaOpen" append-to-body class="form-dialog" width="80%">
      <el-table v-loading="quotaloading" :data="quotaList" :span-method="arraySpanMethod" :header-cell-style="{ background: '#FAFAFA', color: '#000000' }" border>
        <template slot="empty">
          <el-empty :image-size="50" description="暂无额度信息"></el-empty>
        </template>
        <!-- 普通列插槽 -->
        <el-table-column label="信审状态" align="center" prop="ruleName" min-width="120px" show-overflow-tooltip fixed="left">
          <template v-slot="{row}">
            <dict-tag :options="dict.type.credit_review_status" :value="row.creditReviewStatus" />
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" align="center" prop="sortIndex" min-width="120px" show-overflow-tooltip fixed="left" />
        <el-table-column label="信审申请编号" align="center" prop="applicationNo" min-width="180px" show-overflow-tooltip fixed="left" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="120px" show-overflow-tooltip fixed="left" />
        <el-table-column label="客户编号" align="center" prop="customerCode" min-width="120px" show-overflow-tooltip />
        <el-table-column label="业务类型" align="center" prop="businessType" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <dict-tag :options="dict.type.business_type" :value="row.businessType" />
          </template>
        </el-table-column>
        <el-table-column label="产品方案" align="center" prop="planName" min-width="120px" show-overflow-tooltip />
        <el-table-column label="申请类型" align="center" prop="applicationType" min-width="120px" show-overflow-tooltip />
        <el-table-column label="车牌号" align="center" prop="carNo" min-width="120px" show-overflow-tooltip />
        <el-table-column label="车辆类型" align="center" prop="vehicleModel" min-width="120px" show-overflow-tooltip />
        <el-table-column label="车辆款型" align="center" prop="vehicleStyle" min-width="120px" show-overflow-tooltip />
        <el-table-column label="新车采购单价" align="center" prop="purchasePrice" min-width="120px" show-overflow-tooltip />
        <el-table-column label="旧车当前估值" align="center" prop="currentValuation" min-width="120px" show-overflow-tooltip />
        <el-table-column label="新车采购总额" align="center" prop="newCarProcurementAmount" min-width="120px" show-overflow-tooltip />
        <el-table-column label="旧车当前估值总额" align="center" prop="oldCarValuationAmount" min-width="140px" show-overflow-tooltip />
        <el-table-column label="租赁用途" align="center" prop="leasePurpose" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <dict-tag :options="dict.type.rental_purpose" :value="row.leasePurpose" />
          </template>
        </el-table-column>
        <el-table-column label="租赁期限" align="center" prop="leaseTerm" min-width="120px" show-overflow-tooltip />
        <el-table-column label="保证金" align="center" prop="margin" min-width="120px" show-overflow-tooltip />
        <el-table-column label="每期租金" align="center" prop="monthlyRent" min-width="120px" show-overflow-tooltip />
        <el-table-column label="首期租金、比例" align="center" prop="firstInstallmentRentalRatio" min-width="150px" show-overflow-tooltip>
          <template v-slot="{row}">
            <template v-if="row.firstInstallmentRentalRatio">
              {{ row.firstInstallmentRent }} 、{{ row.firstInstallmentRentalRatio }}%
            </template>
            <template v-else>
              -- 、--
            </template>
          </template>
        </el-table-column>
        <el-table-column label="残值、比例" align="center" prop="residualValueRatio" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <template v-if="row.residualValueRatio">
              {{ row.residualValue }} 、 {{ row.residualValueRatio }}%
            </template>
            <template v-else>
              -- 、--
            </template>
          </template>
        </el-table-column>
        <el-table-column label="租金支付方式" align="center" prop="rentPaymentMethod" min-width="120px" show-overflow-tooltip />
        <el-table-column label="申请总台数" align="center" prop="totalApplicationNumber" min-width="120px" show-overflow-tooltip />
        <el-table-column label="信审中总台数" align="center" prop="totalCringNumber" min-width="120px" show-overflow-tooltip />
        <el-table-column label="通过总台数" align="center" prop="totalPassNumber" min-width="120px" show-overflow-tooltip />
        <el-table-column label="拒绝总台数" align="center" prop="totalRejectNumber" min-width="120px" show-overflow-tooltip />
        <el-table-column label="不予准入总台数" align="center" prop="totalNotAdmittedNumber" min-width="120px" show-overflow-tooltip />
        <el-table-column label="撤单总台数" align="center" prop="totalCancelNumber" min-width="120px" show-overflow-tooltip />
        <el-table-column label="申请台数" align="center" prop="numberOfApplications" min-width="120px" show-overflow-tooltip />
        <el-table-column label="通过台数" align="center" prop="numberOfUnitsPassed" min-width="120px" show-overflow-tooltip />
        <el-table-column label="拒绝台数" align="center" prop="rejectedUnits" min-width="120px" show-overflow-tooltip />
        <el-table-column label="已使用台数" align="center" prop="numberOfUnitsUsed" min-width="120px" show-overflow-tooltip />
        <el-table-column label="作废台数" align="center" prop="numberOfInvalidUnits" min-width="120px" show-overflow-tooltip />
        <el-table-column label="冻结台数" align="center" prop="numberOfFrozenUnits" min-width="120px" show-overflow-tooltip />
        <el-table-column label="剩余可使用台数" align="center" prop="numberOfRemainingUnits" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <span>{{ row.numberOfUnitsPassed - row.numberOfUnitsUsed - row.numberOfInvalidUnits - row.numberOfFrozenUnits }}</span>
          </template>
        </el-table-column>
        <el-table-column label="通过台数状态" align="center" prop="effectiveStatus" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <span>{{ row.effectiveStatus|effectiveStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column label="通过台数到期时间" align="center" prop="creditReviewDeadline" min-width="140px" show-overflow-tooltip />
        <el-table-column label="客户类型" align="center" prop="customerType" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <dict-tag :options="dict.type.customer_type" :value="row.customerType" />
          </template>
        </el-table-column>
        <el-table-column label="客户标签" align="center" prop="customerSource" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <dict-tag :options="dict.type.customer_label" :value="row.customerSource" />
          </template>
        </el-table-column>
        <el-table-column label="客户等级" align="center" prop="customerLevel" min-width="100px" show-overflow-tooltip>
          <template v-slot="{row}">
            <dict-tag :options="dict.type.customer_level" :value="row.customerLevel" />
          </template>
        </el-table-column>
        <el-table-column label="客户属性" align="center" prop="clientProperty" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <dict-tag :options="dict.type.customer_property" :value="row.clientProperty" />
          </template>
        </el-table-column>
        <el-table-column label="是否是老客户" align="center" prop="areYouALoyalCustomer" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <dict-tag :options="dict.type.business_yes_no" :value="row.areYouALoyalCustomer" />
          </template>
        </el-table-column>
        <el-table-column label="线索分类" align="center" prop="clueClassification" min-width="120px" show-overflow-tooltip>
          <template v-slot="{row}">
            <dict-tag :options="dict.type.quota_lead_source" :value="row.clueClassification" />
          </template>
        </el-table-column>
        <el-table-column label="车辆厂商" align="center" prop="vehicleManufacturers" min-width="120px" show-overflow-tooltip />
        <el-table-column label="车辆能源类型" align="center" prop="vehicleEnergyType" min-width="120px" show-overflow-tooltip />
        <el-table-column label="登记性质" align="center" prop="registrationNature" min-width="120px" show-overflow-tooltip />
        <el-table-column label="里程限制(公里)" align="center" prop="mileageLimit" min-width="120px" show-overflow-tooltip />
        <el-table-column label="上牌城市" align="center" prop="registeredCity" min-width="120px" show-overflow-tooltip />

        <el-table-column label="额度申请编号" align="center" prop="orderNo" min-width="180px" show-overflow-tooltip />
        <el-table-column label="提交人" align="center" prop="submitter" min-width="120px" show-overflow-tooltip />
        <el-table-column label="提交时间" align="center" prop="submitTime" min-width="120px" show-overflow-tooltip />
        <el-table-column label="受理时间" align="center" prop="handlingTime" min-width="120px" show-overflow-tooltip />
        <el-table-column label="审核时间" align="center" prop="auditTime" min-width="120px" show-overflow-tooltip />
        <el-table-column label="撤单时间" align="center" prop="invalidTime" min-width="120px" show-overflow-tooltip />
        <el-table-column label="审核人" align="center" prop="auditPerson" min-width="120px" show-overflow-tooltip />

      </el-table>

    </el-dialog>

    <!-- 添加或修改测试单表对话框 -->
    <el-dialog title="分配" :visible.sync="openDis" append-to-body width="45%">

      <el-form ref="formDis" :model="formDis" label-width="120px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="选择公司:" prop="deptLabel" :rules="{
                                         required: true,
                                         message: '请选择选择公司',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, formDis.deptIds, callback)
                                       }">
              <el-select
                @change="$forceUpdate()"
                filterable
                v-model="formDis.deptIds"
                clearable multiple
                style="width: 100%">
                <template
                  v-for="(item, index) in belongCompanyList">
                  <el-option
                    :label="item.deptName"
                    :value="item.deptId"
                    :key="index"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button @click="cancelDis">取 消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitDis" >确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import SearchContent from "@/components/SearchContent/index.vue";
import {
  customerDelete,
  customerInvoice, customerInvoiceSet,
  customerStatistics,
  getCustomerList,
  quotaSharing, creditReviewAllDetails, CUSTOMER_EXPORT, IMPORTMEMBER
} from "@/api/memberManage/memberList";
import {cluesTransferRecordAdd, customerDistribution} from "@/api/memberManage/clueList";
import {listDept} from "@/api/system/dept";
import * as app from "@/api/app";

export default {
  name: "MemberList",
  components: {
    SearchContent
  },
  dicts: ['business_scope', 'customer_level', 'customer_property', 'customer_source', 'customer_label',
    'business_yes_no', 'customer_type', 'business_type', 'rental_purpose', 'credit_review_status'],
  data() {
    return {
      timeRange: [],
      //按钮loading
      buttonLoading: false,
      publicLoading: false,
      quotaloading: false,
      // 遮罩层
      loading: true,
      isNew: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      publicOpen: false,
      quotaOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerCode: null,
        customerName: null,
        customerPropertyCode: null,
        customerLevelCode: null,
        createBy: null,
        customerLabelCode: null,
        customerSourceCode: null,
        createStartTime: null,
        createEndTime: null,
        customerUscc: null,
        identityNumber: null,
        saveFlag: null,
        businessScopeCode: '1',
      },

      total: 0,
      dataList: [],
      quotaTotal: 0,
      quotaList: [],
      quotaParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      publicForm: {},
      // 表单校验
      rules: {
        invoiceTitle: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        taxpayerIdentityNumber: [
          { required: true, message: "税号不能为空", trigger: "blur" }
        ],
        bankName: [
          { required: true, message: "开户银行不能为空", trigger: "blur" }
        ],
        bankAccountName: [
          { required: true, message: "账户不能为空", trigger: "blur" }
        ],
      },
      // 表单校验
      publicRules: {
        tagName: [
          { required: true, message: "标签名称不能为空", trigger: "blur" }
        ],
      },
      tabs: [{
        name: '全业务客户总数',
        count: 0,
        check: true
      }, {
        name: '自营客户总数',
        count: 0,
        check: false
      }, {
        name: '渠道客户总数',
        count: 0,
        check: false
      }],
      //非合并列字段集合
      unMergeArr: [
        'applicationType',
        'carNo',
        'vehicleModel',
        'vehicleStyle',
        'purchasePrice',
        'currentValuation',
        'vehicleManufacturers',
        'leaseTerm',
        'rentPaymentMethod',
        'vehicleEnergyType',
        'registrationNature',
        'mileageLimit',
        'registeredCity',
        'numberOfApplications',
        'numberOfUnitsPassed',
        'rejectedUnits',
        'numberOfUnitsUsed',
        'numberOfInvalidUnits',
        'numberOfFrozenUnits',
        'numberOfRemainingUnits',
        'effectiveStatus',
        'margin',
        'monthlyRent',
        'firstInstallmentRentalRatio',
        'residualValueRatio'
      ],
      selMember:null,
      openDis:false,
      formDis:{},
      belongCompanyList:[]
    };
  },
  created() {
    this.getList()
    this.getBelongCompany()
  },
  activated() {
    this.getList()
  },
  methods: {
    validData(rule, value, callback) {
      // console.log('aaa', rule, value, callback)
      if (rule.required && !value) {
        // this.$modal.msgError(`未填写${value}`);
        callback(new Error(rule.message));
      } else {
        callback();
      }
    },
    getBelongCompany() {
      // listDept({
      //   deptType: '2', //组织类型（1部门 2公司）
      //   regionId: null, //所在城市（省市区id）
      // }).then(res => {
      //   this.belongCompanyList = res.data;
      // });

      app.DeptListNoPermission({
        deptType: '2', //组织类型（1部门 2公司）
        regionId: null, //所在城市（省市区id）
      }).then(res => {
        if (res.code == 200) {
          // res?.data?.map(item => {
          //   item.deptId = item.deptId?.toString();
          // });
          this.belongCompanyList = res?.data ?? [];
        }
      });

    },
    // 合并相同编号行
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (!this.unMergeArr.includes(column.property)) {
        return {
          rowspan: row.rowspan,
          colspan: row.rowspan > 0 ? 1 : 0
        }
      }
    },
    // 计算每行数据需要合并的行rowspan，在表格数据更新后进行调用
    setrowspans(list) {
      list.forEach(v => {
        v.rowspan = 1
      })
      // 双层循环
      for (let i = 0; i < list.length; i++) {
        /**
         * 内层循环，上面已经给所有的行都加了v.rowspan = 1
         * 如果当前行的purchaseNo和下一行的purchaseNo相等
         * 就把当前v.rowspan + 1
         * 下一行的v.rowspan - 1
         */
        for (let j = i + 1; j < list.length; j++) {
          // 此处可根据相同字段进行合并，此处是根据的purchaseNo，实际情况根据业务需要修改
          if (list[i].applicationNo === list[j].applicationNo) {
            list[i].rowspan++
            list[j].rowspan--
          } else {
            break
          }
        }
        // 这里跳过已经合并的行数据，从下一次需要合并的行开始
        i = i + list[i].rowspan - 1
      }
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true;

      this.queryParams.createStartTime = this.timeRange && this.timeRange[0] ? this.timeRange[0] : ''
      this.queryParams.createEndTime = this.timeRange && this.timeRange[1] ? this.timeRange[1] : ''


      getCustomerList(this.queryParams).then(res => {
        if (res.code == "200") {
          const { rows, total } = res
          this.dataList = rows
          this.total = total
          this.loading = false;
        }
      });

      customerStatistics(this.queryParams).then(res => {
        this.tabs[0].count = res.data.totalCount
        this.tabs[1].count = res.data.selfOperatedCount
        this.tabs[2].count = res.data.channelCount
      })

    },
    getQuotaList() {

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    publicCancel() {
      this.publicOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.timeRange = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        customerCode: null,
        customerName: null,
        customerPropertyCode: null,
        customerLevelCode: null,
        createBy: null,
        customerLabelCode: null,
        customerSourceCode: null,
        createStartTime: null,
        createEndTime: null,
        customerUscc: null,
        identityNumber: null,
        saveFlag: null,
        businessScopeCode: '1',
      },
        this.tabClick(0)
      // this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增操作 */
    handleAdd() {
      // this.$router.push({
      this._toPage({
        name: 'memberAdd',
        query: { pageType: '新增客户' }
        // query: {orderNo: row.orderNo}
      })
    },

    tabClick(index) {
      this.tabs.forEach((item, i) => {
        item.check = index == i;
      })
      this.queryParams.businessScopeCode = `${index + 1}`
      this.handleQuery()
    },

    /** 转移 */
    handleTransfer(row) {
      this.reset();
      this.open = true;
      // this.isNew = true
      this.title = "开票信息";

      customerInvoice(row.customerId).then(res => {
        this.form = res.data
      }).finally(f => {
        // this.form.customerTypeCode = row.customerTypeCode
        this.$set(this.form, 'customerTypeCode', row.customerTypeCode)
      })
    },
    /** 分配 */
    distribution(row) {
      this.resetDis();
      this.selMember = row;
      this.openDis = true;
      this.formDis.deptIds = row.deptNcIds;
      this.$forceUpdate();
    },

    cancelDis(){
      this.selMember = null;
      this.resetDis();
      this.openDis = false;
    },

    resetDis(){
      this.formDis = {}
      this.resetForm("formDis");
    },

    submitDis(){
      this.$refs["formDis"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;

          customerDistribution({
            deptIds:this.formDis.deptIds,
            customerId: this.selMember.customerId
          }).then(res => {
            this.buttonLoading = false;
            this.$modal.msgSuccess("分配成功");
            this.openDis = false;
            this.resetDis();
            this.handleQuery();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('/customer/customer/export', {
        ...this.queryParams
      }, `客户列表.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$UploadDialog({
        title: "批量添加客户",
        showtoastSureBtn: false,
        showResult: true,
        showErrorFeedback: true,
        uploadConfig: {
          uploadFileUrl: `#${IMPORTMEMBER}`,
          limit: 1,
          params: {},
          fileType: ['xls', 'xlsx'],
          templateUrl: `${CUSTOMER_EXPORT}`,
          templateName: `客户-导入模版.xlsx`,
        },
      }).finally(f => {
        this.handleQuery()
      })
    },
    handleDetail(row) {
      // this.$router.push({
      this._toPage({
        name: 'memberDetail',
        query: { customerId: row.customerId }
      })
    },

    handlePublic(row) {
      // this.reset();
      this.publicOpen = true;
      // this.isNew = true

      quotaSharing(row.customerId).then(res => {
        // this.quotaShareList = res.data;
      })
    },

    handleQuota(row) {
      // this.reset();
      this.quotaOpen = true;

      this.quotaloading = true
      creditReviewAllDetails({
        customerNo: row.customerId,
        tabType: 6
      }).then(res => {
        this.quotaList = res.data
        this.setrowspans(this.quotaList)
      }).finally(f => {
        this.quotaloading = false
      })

      // this.isNew = true

    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.$router.push({
      this._toPage({
        name: 'memberAdd',
        query: { customerId: row.customerId, pageType: '编辑客户' }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('确定删除？').then(() => {
        this.loading = true;
        return customerDelete(row.customerId);
      }).then(() => {
        this.loading = false;
        this.handleQuery();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });

    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          customerInvoiceSet(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.handleQuery();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },

  }
};
</script>


<style lang="scss" scoped>
.pagination-container {
  padding: 0 20px 50px !important;
}

.form-dialog {
  ::v-deep .el-dialog__header {
    padding: 10px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__headerbtn {
      top: 15px;
    }
  }

  .box-card {
    margin-bottom: 20px;

    .card-title {
      font-size: 16px;
      position: relative;
      margin-left: 8px;
      padding: 0;
    }

    .card-title::after {
      content: "";
      width: 4px;
      height: 18px;
      background-color: aqua;
      display: block;
      position: absolute;
      left: -12px;
      top: 2px;
    }
  }
}
</style>
